package com.snack.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.snack.shop.common.BusinessException;
import com.snack.shop.entity.Product;
import com.snack.shop.mapper.ProductMapper;
import com.snack.shop.service.FileManageService;
import com.snack.shop.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;

/**
 * 商品服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ProductServiceImpl implements ProductService {

    private final ProductMapper productMapper;
    private final FileManageService fileManageService;

    @Override
    public Page<Product> page(Long categoryId, Integer current, Integer size, Integer status, Boolean lowStock, Integer stockThreshold, String keyword) {
        Page<Product> page = new Page<>(current, size);
        
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        
        // 如果分类ID不为0，则查询指定分类
        if (categoryId != null && categoryId > 0) {
            wrapper.eq(Product::getCategoryId, categoryId);
        }
        
        // 如果指定了状态，则查询指定状态的商品
        if (status != null) {
            wrapper.eq(Product::getStatus, status);
        }
        
        // 库存预警筛选：库存小于等于阈值（默认10）
        if (Boolean.TRUE.equals(lowStock)) {
            int threshold = (stockThreshold != null ? stockThreshold : 10);
            wrapper.le(Product::getStock, threshold);
        }
        
        // 关键词模糊搜索（名称/描述）
        if (keyword != null && !keyword.trim().isEmpty()) {
            String kw = keyword.trim();
            wrapper.and(w -> w.like(Product::getName, kw)
                               .or()
                               .like(Product::getDescription, kw));
        }
        
        // 按创建时间倒序排序
        wrapper.orderByDesc(Product::getCreateTime);
        
        return productMapper.selectPage(page, wrapper);
    }

    @Override
    public Product getDetail(Long productId) {
        return productMapper.selectById(productId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Product product) {
        String oldImage = null;
        
        // 如果是编辑，获取旧图片
        if (product.getId() != null) {
            Product oldProduct = productMapper.selectById(product.getId());
            if (oldProduct != null) {
                oldImage = oldProduct.getImage();
            }
        }
        
        if (product.getId() == null) {
            // 新增
            productMapper.insert(product);
        } else {
            // 编辑
            productMapper.updateById(product);
        }
        
        // ✅ 确认商品图片为正式状态
        try {
            if (product.getImage() != null && !product.getImage().trim().isEmpty()) {
                fileManageService.confirmFiles(
                    Collections.singletonList(product.getImage()),
                    "product",
                    product.getId()
                );
                log.info("确认商品图片为正式状态: productId={}, image={}", product.getId(), product.getImage());
            }
            
            // ✅ 如果更换了图片，标记旧图片为已删除
            if (oldImage != null && !oldImage.equals(product.getImage())) {
                fileManageService.markDeleted(Collections.singletonList(oldImage));
                log.info("标记旧商品图片为已删除: productId={}, oldImage={}", product.getId(), oldImage);
            }
        } catch (Exception e) {
            log.error("处理商品图片失败", e);
            // 不影响主流程
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long productId, Integer status) {
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        LambdaUpdateWrapper<Product> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Product::getId, productId)
               .set(Product::getStatus, status);
        
        productMapper.update(null, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long productId) {
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        // ✅ 标记商品图片为已删除
        try {
            if (product.getImage() != null && !product.getImage().trim().isEmpty()) {
                fileManageService.markDeleted(Collections.singletonList(product.getImage()));
                log.info("标记商品图片为已删除: productId={}, image={}", productId, product.getImage());
            }
        } catch (Exception e) {
            log.error("标记商品图片失败", e);
            // 不影响主流程
        }
        
        // 逻辑删除
        productMapper.deleteById(productId);
    }
}

